package com.ly.hotel.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.RSAUtils;
import com.ly.hotel.common.SharedPreferencesConfig;
import com.ly.hotel.common.SysConf;
import com.ly.hotel.model.Ad;
import com.ly.hotel.model.AdDetail;
import com.ly.hotel.model.AppBean;
import com.ly.hotel.model.AppInfo;
import com.ly.hotel.model.BackgroundInfo;
import com.ly.hotel.model.Device;
import com.ly.hotel.model.DeviceInfo;
import com.ly.hotel.model.Episodepart;
import com.ly.hotel.model.ExpConfInfo;
import com.ly.hotel.model.GroupName;
import com.ly.hotel.model.IconAnimationBean;
import com.ly.hotel.model.IconAnimationDetail;
import com.ly.hotel.model.LiveManagement;
import com.ly.hotel.model.ScrollMessage;
import com.ly.hotel.model.SeatPicInfo;
import com.ly.hotel.model.StartUpGuideInfo;
import com.ly.hotel.model.Vodvideo;
import com.ly.hotel.model.WebInterfaceApp;
import com.ly.hotel.model.YouhuiMessage;
import com.ly.hotel.model.ModelBean;
import com.ly.hotel.model.MusicAlbumPageBean;
import com.ly.hotel.model.MusicBean;
import com.ly.hotel.model.MusicPageBean;
import com.ly.hotel.model.Serve;
import com.ly.hotel.model.Soft;
import com.ly.hotel.model.Vodpart;
import com.ly.hotel.model.VodVideoBean;
import com.ly.hotel.util.BtnCfgUtil;
import com.ly.hotel.util.HttpHelper;
import com.ly.hotel.util.HttpRequestFailException;
import com.ly.hotel.util.HttpUtil;
import com.ly.hotel.util.LyStringUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;
import com.ly.hotel.webagent.HttpRequest;

public class SPAService {
	private static final Gson gson = new GsonBuilder().create();

	// 格式 http://192.168.2.250:40000/

	public final static String PROJECT = "";// premier-sys
	public static boolean zipDownloading = false;
	

	public static List<LiveManagement> getLiveList(String mac) throws GetDataException {
		Log.i("live","获取直播数据...");
		try {
			String url1 = MyApplication.getHost() + PROJECT + "/api/tvs.json";
			String result1 = HttpUtil.requestGet(url1, paramMac(mac), null, null);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
				return null;

			LiveManagement[] sb = (LiveManagement[]) d.getData(LiveManagement[].class);

			List<LiveManagement> list = Arrays.asList(sb);

			return list;

		} catch (Throwable e) {
			Log.e("live", "直播数据获取失败:" + e.getMessage());
//			throw new GetDataException(e);
			return null;
		}
	}

	/**
	 * 音乐(获取所有专辑)
	 * @param mac
	 *            本机的MAC地址
	 * @return MusicAlbumPageBean
	 * @throws GetDataException
	 */
	public static MusicAlbumPageBean getMusicAlbums(String mac) throws GetDataException {
		Log.i("music", "获取区域的专辑...");

		try {
			String url = MyApplication.getHost() + PROJECT + "/api/music-album.json?size=10000";
			String result1 = HttpUtil.requestGet(url, paramMac(mac), null, null);
			Log.i("music", "url =" + url);
			// Log.i("vod", "result =" + result1);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
				return null;

			MusicAlbumPageBean vp = (MusicAlbumPageBean) d.getData(MusicAlbumPageBean.class);
			return vp;

		} catch (JsonSyntaxException e) {
			Log.e("music", "音乐专辑数据获取失败:" + e.getMessage());
		}
		return null;
	}

	/**
	 * @param albumId
	 *            专辑ID,一次性获取一个专辑的所有歌，数量不多，没必要分页
	 * @param mac
	 *            本机的MAC地址
	 * @return
	 * @throws GetDataException
	 */
	public static MusicPageBean getMusics(int albumId, String mac) throws GetDataException {
		Log.i("music", "获取专辑的歌...");

		try {
			String url = MyApplication.getHost() + PROJECT + "/api/music.json?size=10000&albumId=" + albumId;
			String result1 = HttpUtil.requestGet(url, paramMac(mac), null, null);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
				return null;

			MusicPageBean vp = (MusicPageBean) d.getData(MusicPageBean.class);

			for (MusicBean l : vp.getMusics()) {
				System.out.println(l.getAddr());
			}
			return vp;

		} catch (JsonSyntaxException e) {
			Log.e("music", "音乐专辑数据获取失败:" + e.getMessage());
		}
		return null;
	}

	// 获取视频类型的列表
	public static List<Vodpart> getAllVideosType(String mac) {
		try {
			String url1 = MyApplication.getHost() + PROJECT + "/api/movie-type.json";
			String result1 = HttpUtil.requestGet(url1, paramMac(mac), null, null);
	 		Log.i("vod", "url =" + url1);
			Log.i("vod", "result =" + result1);

			if (result1 == null)
				return null;
 
			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
				return null;

			Vodpart[] vp = (Vodpart[]) d.getData(Vodpart[].class);
			
			List<Vodpart> list = new ArrayList<Vodpart>(); 

			list.addAll(Arrays.asList(vp));
			
			return list;

		} catch (JsonSyntaxException e) {
			Log.e("movie", "电影类型数据获取失败:" + e.getMessage());
		}
		return null;
	}

	// 获取全部电视剧的列表
	public static List<Episodepart> getAllEpisodeType(String mac) {
		try {
			String url1 = MyApplication.getHost() + PROJECT + "/api/movie-type-one.json?prefix=TV_";
			String result1 = HttpUtil.requestGet(url1, paramMac(mac), null, null);
			Log.i("vod", "url =" + url1);
			Log.i("vod", "result =" + result1);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
				return null;

			Episodepart[] vp = (Episodepart[]) d.getData(Episodepart[].class);

			List<Episodepart> list = new ArrayList<Episodepart>();
			list.addAll(Arrays.asList(vp));
			return list;

		} catch (JsonSyntaxException e) {
			Log.e("movie", "电视剧类型数据获取失败:" + e.getMessage());
		}
		return null;
	}

	// 获取视频内容列表
	public static List<Vodvideo> getAllVodList(String mac) {
		try {
			
			String url1 = null;
			
			url1 = MyApplication.getHost() + PROJECT + "/api/movies.json" + "?no=" + 1 + "&size=" + 100000;

			String result1 = HttpUtil.requestGet(url1, paramMac(mac), null, null);
			Log.i("Vodvideo", "url =" + url1);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
				return null;

			VodVideoBean vvb = gson.fromJson(d.getData().toString(), VodVideoBean.class);

			return vvb.getMovies();

		} catch (JsonSyntaxException e) {
			Log.e("movie", "视频内容数据获取失败:" + e.getMessage());
		}
		return null;
	}

	
	// 获取视频内容列表
	public static VodVideoBean getVodList(String mac, int type, int no, int size, String name, Integer id) {
		try {
			
			String url1 = null;
			
			if(name != null){
				//搜索电影
				url1 = MyApplication.getHost() + PROJECT + "/api/movies.json" + "?name=" + name + "&no=" + no + "&tag=&size=" + size;
			}else if(id != null){
				//获取电影信息
				url1 = MyApplication.getHost() + PROJECT + "/api/movies.json" + "?id=" + id;
			}else{
				//获取电影列表
				url1 = MyApplication.getHost() + PROJECT + "/api/movies.json" + "?type=" + type + "&no=" + no + "&size=" + size;
			}
			String result1 = HttpUtil.requestGet(url1, paramMac(mac), null, null);
			Log.i("Vodvideo", "url =" + url1);
			// Log.i("Vodvideo", "result =" + result1);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
				return null;

			// System.out.println("ModelBean date:" + d.getData().toString());

			VodVideoBean vvb = gson.fromJson(d.getData().toString(), VodVideoBean.class);
			/*if(vvb != null){
				//对类别列表进行排序
		        Collections.sort(vvb.getMovies(), new Comparator<Vodvideo>() {

					@Override
					public int compare(Vodvideo v1, Vodvideo v2) {
						// TODO Auto-generated method stub
						return v1.getPriority().compareTo(v2.getPriority());
					}
				});
			}*/
			return vvb;

		} catch (JsonSyntaxException e) {
			Log.e("movie", "视频内容数据获取失败:" + e.getMessage());
		}
		return null;
	}

	// 应用
	public static List<AppInfo> getAppInfos(String mac) {
		try {
			String url = MyApplication.getHost() + PROJECT + "/api/game.json?size=1000";
			String result1 = HttpUtil.requestGet(url, paramMac(mac), null, null);
			Log.i("app", "url =" + url);
			// Log.i("app", "result =" + result1);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d != null) {
				if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
					return null;

				AppBean ab = (AppBean) d.getData(AppBean.class);

				if (ab != null) {
					 //根据Collections.sort重载方法来实现  
			        Collections.sort(ab.getApps(),new Comparator<AppInfo>(){  
						@Override
						public int compare(AppInfo a1, AppInfo a2) {
							// TODO Auto-generated method stub
							return a1.getPriority().compareTo(a2.getPriority());
						}  
			              
			        });  
					/*
					 * for (AppInfo b : ab.getApps()) { // 不带参数返回的是顶层的数据
					 * Log.i("apps", b.getAppName() + b.getIcon());
					 * 
					 * }
					 */

					return ab.getApps();
				}
			}
		} catch (JsonSyntaxException e) {
			Log.e("game", "游戏数据获取失败:" + e.getMessage());
		}
		return null;
	}

	// 软件升级
	public static Soft checkSoftUpdate(String mac ,String versionName, int version) {

		try {
			String result1 = null;
			String rootVersion[] = versionName.split("\\.");//例如1.6.555中的1.6就是rootVersion
			if(rootVersion.length != 2){
				Log.e("update", "版本号参数不正确!");
				return null;
			}
			
			for(int index=0;index<160;index++){
				
				String url = MyApplication.getHost() + PROJECT + "/api/sys-apk.json?mac=" + mac + "&index=" + index;
				result1 = HttpHelper.getStringSync(null, url);
	
				 Log.i("update", "url =" + url);
				 Log.i("update", "result =" + result1);
	
				if (result1 == null){
					return null; 
				}else{
					
					ModelBean d = gson.fromJson(result1, ModelBean.class);

					if (d != null) {
						if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
							return null;

						Soft soft = (Soft) d.getData(Soft.class);
						if (soft != null) {
							
							if(soft.getFullversion() != null){
								String s[] = soft.getFullversion().split("\\.");
//								Log.i("update", "s.length =" + s.length + ",s[0]=" + s[0] + ",v[0]=" +v[0]);
								if(s.length == 3 && s[0].equals(rootVersion[0])){
									Log.i("update", "主版本正确");
									if(version < soft.getVersion()){
										return soft;
									} else {
										//版本号太小，查找下一个
										continue;
									}
								}else{
									//不是我的主版本号，就继续查找下一个
									continue;
								}
							}else{
								d = null;
								continue;
							}
						}
					}
				}
			}

		} catch (Exception e) {
			Log.e("update", "升级数据获取失败:" + e.getMessage());
		}

		return null;
	}

	public static List<AppInfo> getThirdApp(String mac) {
		// 通过自己的ID获取子列表
		try {
			String url = MyApplication.getHost() + PROJECT + "/api/app.json?size=1000";
			String result1 = HttpUtil.requestGet(url, paramMac(mac), null, null);
			Log.i("app", "url =" + url);
			// Log.i("app", "result =" + result1);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d != null) {
				if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
					return null;

				AppBean ab = (AppBean) d.getData(AppBean.class);

				if (ab != null) {
					 //根据Collections.sort重载方法来实现  
			        Collections.sort(ab.getApps(),new Comparator<AppInfo>(){  
						@Override
						public int compare(AppInfo a1, AppInfo a2) {
							// TODO Auto-generated method stub
							return a1.getPriority().compareTo(a2.getPriority());
						}  
			              
			        }); 

					return ab.getApps();
				}
			}
		} catch (JsonSyntaxException e) {
			Log.e("app", "游戏数据获取失败:" + e.getMessage());
		}
		return null;
	}

	public static String getServerApiVersion(String mac) {

		String url = MyApplication.getHost() + PROJECT + "/api/version-api.json";
		String result = HttpUtil.requestGet(url, paramMac(mac), null, null);

		ModelBean d1 = gson.fromJson(result, ModelBean.class);

		if (result == null)
			return null;

		if (d1.getCode().equals(-1))
			return null;

		return d1.getData().toString();
	}

	public static String getWifiConfig() {

		String url = MyApplication.getHost() + PROJECT + "/api/dbfile-read.json";
		String request = "filename=WifiInfo";
		Log.i("httpGet", url + "?" + request);
		String result = HttpRequest.sendGet(url, request);

		ModelBean d1 = gson.fromJson(result, ModelBean.class);

		if (result == null)
			return null;

		if (d1.getCode() != 200)
			return null;

		return d1.getData().toString();
	}
	
	private static Serve[] getSubServeIntroduce(Serve se, String mac) {
		// 通过自己的ID获取子列表
		String url1 = MyApplication.getHost() + PROJECT + "/api/serve.json?id=" + se.getId();

		String result1 = HttpUtil.requestGet(url1, paramMac(mac), null, null);
		// Log.i("intor_sub", "url =" + url1);
		// Log.i("intor_sub", "result =" + result1);

		ModelBean d1 = gson.fromJson(result1, ModelBean.class);

		if (result1 == null)
			return null;

		if (d1.getCode().equals(-1))
			return null;

		Serve[] sb1 = (Serve[]) d1.getData(Serve[].class);

		return sb1;
	}

	// 本地介绍
	public static List<Serve> getAllServeIntroduce(String mac) {
		Log.i("intro","本地介绍...");
		List<Serve> mainList = new ArrayList<Serve>();
		List<Serve> list = new ArrayList<Serve>();
		List<Serve> list_sub = new ArrayList<Serve>();
		List<Serve> list_sub_sub = new ArrayList<Serve>();
		try {
			String url = MyApplication.getHost() + PROJECT + "/api/serve.json";
			String result1 = HttpUtil.requestGet(url, paramMac(mac), null, null);
			Log.i("intro", "url =" + url);
			// Log.i("intor", "result =" + result1);

			if (result1 == null)
				return null;

			ModelBean bean = gson.fromJson(result1, ModelBean.class);

			if (bean != null) {
				if (bean.getCode().equals(-1) || bean.getData() == null)
					return null;

				Serve[] sb = (Serve[]) bean.getData(Serve[].class);

				if (sb != null) {
					for (Serve b : sb) {
						// 顶层的数据全面加进去
						// Log.i("intro", "add b =" + b.getName());
						mainList.add(b);// 顶层+第一数据子层

						if (b.getSon() == true) {
							// Log.i("intro", "b has son");
							Serve[] sb_sub = getSubServeIntroduce(b, mac);// 第二数据子层+第三数据子层
							if (sb_sub != null) {
								list = Arrays.asList(sb_sub);
								b.setSiList(list);

								for (Serve c : b.getSiList()) {
									// Log.i("intro", "c =" + c.getName());
									if (c.getSon() == true) {
										// Log.i("intro", "c has son");
										Serve[] sb_sub_sub = getSubServeIntroduce(c, mac);// 第四数据子层+第五数据子层
										list_sub = Arrays.asList(sb_sub_sub);
										for (Serve d : list_sub) {
											// Log.i("intro", "e =" +
											// d.getName());

											if (d.getSon() == true) {
												// Log.i("intro", "e has son");
												Serve[] sb_sub_sub_sub = getSubServeIntroduce(d, mac);// 第四数据子层+第五数据子层
												list_sub_sub = Arrays.asList(sb_sub_sub_sub);
												/*
												 * for (Serve e : list_sub_sub)
												 * { Log.i("intor", "d =" +
												 * e.getName()); }
												 */
												d.setSiList(list_sub_sub);
											}
										}
										c.setSiList(list_sub);
									}
								}
							}
						}
					}
					
					if(mainList != null){
						Collections.sort(mainList,new Comparator<Serve>(){  
							@Override
							public int compare(Serve s1, Serve s2) {
								// TODO Auto-generated method stub
								return s1.getPriority().compareTo(s2.getPriority());
							}  
				        }); 
					}
					return mainList;
				}
			}
		} catch (JsonSyntaxException e) {
			Log.e("intor", "介绍数据获取失败:" + e.getMessage());
		}
		return null;
	}

	public static Ad getAdInfo(String mac, int type) {
		// Log.i("ad", "广告数据...");
		String url = MyApplication.getHost() + PROJECT + "/api/serve-ad.json?mac=" + mac + "&type=" + type;
		// Log.i("ad", "url =" + url);
		try {
			String result = HttpHelper.getStringSync(null, url);

			// Log.i("ad", "result =" + result);

			if (result == null)
				return null;

			ModelBean b = gson.fromJson(result, ModelBean.class);

			if (b != null) {
				if (b.getCode().equals(-1) || b.getData() == null || b.getData().equals(""))
					return null;

				// Log.i("ad", "b.getData =" + b.getData());

				AdDetail[] sb = (AdDetail[]) b.getData(AdDetail[].class);

				if (sb != null) {
					Ad a = new Ad();
					a.setType(type);
					a.setDetails(Arrays.asList(sb));
					return a;
				} else {
					return null;
				}
			}

			return null;
		} catch (Throwable e) {
			Log.e("ad", "广告数据获取失败:" + e.getMessage());
			e.printStackTrace();

		}
		return null;
	}

	public static Ad getPowerOnAdInfo(String mac) {
		Log.i("ad", "开机广告数据...");
		String url = MyApplication.getHost() + PROJECT + "/api/on-ad.json?mac=" + mac;
		Log.i("ad", "url =" + url);
		try {
			String result = HttpHelper.getStringSync(null, url);

			Log.i("ad", "result =" + result);

			if (result == null)
				return null;

			ModelBean b = gson.fromJson(result, ModelBean.class);

			if (b != null) {
				if (b.getCode().equals(-1) || b.getData() == null || b.getData().equals(""))
					return null;

				// Log.i("ad", "b.getData =" + b.getData());

				AdDetail[] sb = (AdDetail[]) b.getData(AdDetail[].class);

				if (sb != null) {
					Ad a = new Ad();
					// a.setType(a);
					a.setDetails(Arrays.asList(sb));
					return a;
				} else {
					return null;
				}
			}

			return null;
		} catch (Throwable e) {
			Log.e("ad", "广告数据获取失败:" + e.getMessage());
			e.printStackTrace();

		}
		return null;
	}

	// 优惠信息
	public static List<YouhuiMessage> getYouhuiMsg(String mac) throws GetDataException {
		Log.i("youhui", "获取优惠消息数据...");
		try {
			String url = MyApplication.getHost() + PROJECT + "/api/coupon.json?mac=" + mac;
			String result1 = HttpHelper.getStringSync(null, url);

			Log.i("youhui", "url =" + url);
			// Log.i("youhui", "result =" + result1);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d != null) {
				if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
					return null;

				YouhuiMessage[] msg = (YouhuiMessage[]) d.getData(YouhuiMessage[].class);
				List<YouhuiMessage> msgList = new Vector<YouhuiMessage>();

				for (YouhuiMessage m : msg) {
					if (m.getStatus() == 1) {
						msgList.add(m);
					}
				}

				if (msgList != null) {
					//逆序，这样就和后台的顺序相同
					Collections.reverse(msgList);//逆序排序  
					
					return msgList;
				}
			}
		} catch (HttpRequestFailException e) {
			Log.e("youhi", "优惠数据获取失败:" + e.getMessage());
		}

		return null;
	}

	// 滚动信息
	public static List<ScrollMessage> getscrollMsg(String mac) throws GetDataException {
		try {
			String url = MyApplication.getHost() + PROJECT + "/api/roll-message.json?mac=" + mac;
			String result1 = HttpHelper.getStringSync(null, url);

			// Log.i("msg", "url =" + url);
			// Log.i("msg", "result =" + result1);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d != null) {
				if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
					return null;

				ScrollMessage[] msg = (ScrollMessage[]) d.getData(ScrollMessage[].class);

				List<ScrollMessage> msgList = Arrays.asList(msg);

				if (msgList != null) {
					return msgList;
				}
			}
		} catch (HttpRequestFailException e) {
			Log.e("msg", "滚动消息数据获取失败:" + e.getMessage());
		}

		return null;
	}

	// 获取首页图片
	public static List<IconAnimationDetail> getIconAnimation(String mac) {
		Log.i("modules", "获取首页图片轮播数据...");
		try {
			String url = MyApplication.getHost() + PROJECT + "/api/modules.json?mac=" + mac;
			String result1 = HttpHelper.getStringSync(null, url);

			Log.i("modules", "url =" + url);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d != null) {
				if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
					return null;

				IconAnimationDetail[] icons = (IconAnimationDetail[]) d.getData(IconAnimationDetail[].class);
				if (icons != null) {
					List<IconAnimationDetail> list = Arrays.asList(icons);

					for (IconAnimationDetail a : list) {
						Iterator<IconAnimationBean> iter = a.getImgs().iterator();
						while (iter.hasNext()) {
							IconAnimationBean b = iter.next();
							if (!b.isEnable()) {
								iter.remove();
							}
						}
					}

					return list;
				}
			}
		} catch (HttpRequestFailException e) {
			Log.e("modules", "首页图片轮播数据获取失败:" + e.getMessage());
		}
		return null;
	}

	public static StartUpGuideInfo getStartUpHelpPic(String mac) throws GetDataException {
		Log.i("startUppic", "获取startUppic数据...");
		try {
			String url = MyApplication.getHost() + PROJECT + "/api/logo.json?mac=" + mac;
			String result1 = HttpHelper.getStringSync(null, url);

			Log.i("startUppic", "url =" + url);
			Log.i("startUppic", "result =" + result1);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d != null) {
				if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
					return null;

				StartUpGuideInfo logo = (StartUpGuideInfo) d.getData(StartUpGuideInfo.class);

				if (logo != null) {
					return logo;
				}
			}
		} catch (HttpRequestFailException e) {
			Log.e("startUppic", "startUppic数据获取失败:" + e.getMessage());
		}

		return null;
	}
	
	// 获取背景
	public static BackgroundInfo getBackground(String mac) throws GetDataException {
		Log.i("background", "获取bg数据...");
		try {
			String url = MyApplication.getHost() + PROJECT + "/api/background.json?mac=" + mac;
			String result1 = HttpHelper.getStringSync(null, url);

			Log.i("background", "url =" + url);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d != null) {
				if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
					return null;

				BackgroundInfo bg = (BackgroundInfo) d.getData(BackgroundInfo.class);

				if (bg != null) {
					Log.i("background", bg.getPath());
					return bg;
				}
			}
		} catch (HttpRequestFailException e) {
			Log.e("bg", "背景数据获取失败:" + e.getMessage());
		}

		return null;
	}

	// 获取背景
	public static SeatPicInfo getSeatPicUrl(String mac) throws GetDataException {
		Log.i("seatpic", "获取留位图片数据...");
		try {
			String url = MyApplication.getHost() + PROJECT + "/api/seat.json?mac=" + mac;
			String result1 = HttpHelper.getStringSync(null, url);

			Log.i("seatpic", "url =" + url);
			// Log.i("background", "result =" + result1);

			if (result1 == null)
				return null;

			ModelBean d = gson.fromJson(result1, ModelBean.class);

			if (d != null) {
				if (d.getCode().equals(-1) || d.getData() == null || d.getData().equals(""))
					return null;

				SeatPicInfo bg = (SeatPicInfo) d.getData(SeatPicInfo.class);

				if (bg != null) {
					Log.i("seatpic", bg.getPath());
					return bg;
				}
			}
		} catch (HttpRequestFailException e) {
			Log.e("seatpic", "背景数据获取失败:" + e.getMessage());
		}

		return null;
	}

	
	public static Device login(String mac) throws HttpRequestFailException {
		Log.i("login", "连接中................." + mac);
		String url = MyApplication.getHost() + PROJECT + "/api/online.json?mac=" + mac;
		String result = HttpHelper.getStringSync(null, url);
		Log.i("login", "result" + result);

		ModelBean d = gson.fromJson(result, ModelBean.class);
		if (!d.getCode().equals(-1)) {
			
			Device device = (Device)gson.fromJson(d.getData().toString(), Device.class);

			if (device != null) {
				Log.i("login", "登陆完成..." + device.getCategoryName());
				return device;
			}
		}
		return null;
	}

	public static String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	public static boolean getUKey(String mac, MyApplication app) throws HttpRequestFailException {
		String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDauKzUbd/SGAhGsdFXWZBsSR3mdPpDi3yXh3irErDf8EPdAVOFlSMV5Qf6OJPuWrz8BbsyKEFC5U3VbGctsEqb90W9eLcsQ8XVibiOIcl/8h9kVbPAoyfKV+oiSEB4IbH7YkrQVDgKEMXvwUamhl/KMbyj8q8sZTDbJlOchBBx6wIDAQAB";
		String url = MyApplication.getHost() + PROJECT + "/api/getUKey.json?mac=" + mac;
		String result = HttpHelper.getStringSync(null, url);
		Log.i("Ukey", "result" + result);
		ModelBean d = gson.fromJson(result, ModelBean.class);
		if (d != null && !d.getCode().equals(-1) && d.getData() != null && !d.getData().equals("")) {
			try {
				String retStr = new String(RSAUtils.decryptByPublicKey(LyStringUtil.hexStringToBytes(d.getData().toString()),
						publicKey), "GBK");

				Log.i("Ukey", retStr);
				String key = "深圳普瑞尔智能技术有限公司-版权所有";
				String key_old = "深圳市普瑞尔实业有限公司-版权所有";
				String[] list = retStr.split(",");
				Log.i("Ukey", "授权信息:" + list[1]);
				MyApplication.setAuthToCompany(list[1]);
				if (TextUtils.isEmpty(SharedPreferencesConfig.getAuthToCompany(MyApplication.getContext()))){
					SharedPreferencesConfig.setAuthToCompany(MyApplication.getContext(),list[1]);
				}

				//解析权限信息,数据是这样的:
				//账号_终端_互动_广告_个性_介绍_技师_消费_电影_电视_音乐_游戏_应用_优惠_系统_维护_关于_呼叫_留位-1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1
				MyApplication.ukeyInvalidTime = list[3];
				Log.i("Ukey", "权限信息:" + list[6]);
				String[] tmp = list[6].split("-");
				if(tmp.length == 2){
					String[] mkey = tmp[0].split("_");//账号_终端_互动_广告_个性_介绍_技师_消费_电影_电视_音乐_游戏_应用_优惠_系统_维护_关于_呼叫_留位
					String[] mvalue = tmp[1].split("_");//1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1_1

					if(mkey.length == mvalue.length){
						for(int i=0;i<mkey.length;i++){
							MyApplication.myLicensePutValue(mkey[i], Integer.parseInt(mvalue[i]));
							
							//顺便初始化按键
							boolean state = false;
							if(MyApplication.myLicenseGetValue(mkey[i]) == 1){
								state = true;
							}
							//是否显示按键
							BtnCfgUtil.setBtnItemInfo(app, mkey[i],state);
							//是否响应按键
							app.setBtnItemRespond(mkey[i], state);
						}
						
						if (MyApplication.myLicenseGetValue("广告").equals(1)) {
							Log.i("Ukey", "支持广告");
							MyApplication.adEnable = true;
						}
					}else{
						Log.e("Ukey", "权限信息不匹配:" + list[6]);
					}
				}else{
					Log.e("Ukey", "权限信息不匹配:" + list[6]);
				}
				
				//查看key是否一致
				for (String a : list) {
					if (a.contains(key) || a.contains(key_old)) {
						Log.e("Ukey", "匹配成功！");
						return true;
					} else {
						return false;
					}
				}

			} catch (Exception e) {
				Log.e("Ukey", e.getMessage()+"");
			}
		}else if(d.getData() == null || d.getData().equals("")){
			Log.e("Ukey", "后台读取U盾成功，但是没有数据？松了？");
			throw new HttpRequestFailException("can not get ukey data.");
		}

		return false;
	}

	//指定位置插入相应的字符
	public static String[] InsertString(String[] array,String string,int index){
		String[] newArray = new String[array.length+1];
		for(int i=0;i < array.length;i++){
			if(i >= index){
				newArray[i+1] = array[i];
			}else{
				newArray[i] = array[i];
			}
		}
		newArray[index] = string;
		return newArray;
	}

	// 获取插件开发码
	public static String getPluginAuthCode() throws HttpRequestFailException {
		String url = MyApplication.getHost() + PROJECT + "/api/plugin-auth.json";
//		Log.i("plugin", "url=" + url);
		String result = HttpHelper.getStringSync(null, url);
//		Log.i("plugin", "result=" + result);

		ModelBean d = gson.fromJson(result, ModelBean.class);
		if (!d.getCode().equals(-1) && d.getData() != null) {
			return d.getData().toString();
		} else {
			return null;
		}
	}

	public static List<String> getAllGroup() throws HttpRequestFailException {
		String url = MyApplication.getHost() + PROJECT + "/api/equipment-category-name.json";
//		Log.i("plugin", "url=" + url);
		String result = HttpHelper.getStringSync(null, url);
		Log.i("group", "result=" + result);
		List<String> list = new ArrayList<String>();
		ModelBean d = gson.fromJson(result, ModelBean.class);
		if (!d.getCode().equals(-1) && d.getData() != null) {
			
			GroupName[] group = (GroupName[]) d.getData(GroupName[].class);

			if (group != null) {
				for(GroupName g : group){
					list.add(g.getId() + "," + g.getName());
				}
				
				return list;
			}
			
		}
		
		return null;
	}
	
	public static ModelBean getUpdateMac(String oldMac, String newMac) throws HttpRequestFailException {
		String url = MyApplication.getHost() + PROJECT + "/api/update-mac.json?oldmac=" + oldMac + "&newmac=" + newMac;
//		Log.i("plugin", "url=" + url);
		String result = HttpHelper.getStringSync(null, url);
		Log.i("group", "result=" + result);
		ModelBean d = gson.fromJson(result, ModelBean.class);

		return d;
	}
	
	public static ModelBean getUpdateDeviceInfo(String newGroupId, String newDeviceName) throws HttpRequestFailException {
		String url = MyApplication.getHost() + PROJECT + "/api/equipment-update.json?mac=" + MyApplication.getMAC() + "&categoryId=" + newGroupId
																						+ "&name=" + newDeviceName;
//		Log.i("plugin", "url=" + url);
		String result = HttpHelper.getStringSync(null, url);
		Log.i("group", "result=" + result);
		ModelBean d = gson.fromJson(result, ModelBean.class);

		return d;
	}
	
	public static List<DeviceInfo> getGroupDevice(String groupName) throws HttpRequestFailException {
		String url = MyApplication.getHost() + PROJECT + "/api/equipment-category-list.json?name=" + groupName;
//		Log.i("plugin", "url=" + url);
		String result = HttpHelper.getStringSync(null, url);
		Log.i("group", "result=" + result);
		List<DeviceInfo> list = new ArrayList<DeviceInfo>();
		ModelBean d = gson.fromJson(result, ModelBean.class);
		if (!d.getCode().equals(-1) && d.getData() != null) {
			
			DeviceInfo[] group = (DeviceInfo[]) d.getData(DeviceInfo[].class);

			if (group != null) {
				
				for(DeviceInfo dev : group){
					list.add(dev);
				}
				return list;
			}
			
		}
		
		return null;
	}
	/* 发送数据给服务器，简单的单向post */
	public static String myHttpPostMsg(String url) throws HttpRequestFailException {
		String result = HttpHelper.getStringSync(null, url);
		// Logger.i("result" + result);

		ModelBean d = gson.fromJson(result, ModelBean.class);
		if (!d.getCode().equals(-1) && d.getData() != null) {
			return d.getData().toString();
		} else {
			return null;
		}
	}

	public static String getWebAppUrl(String mac) throws HttpRequestFailException {
		String url = MyApplication.getHost() + PROJECT + "/api/interface-version.json?mac=" + mac;
		String result = HttpHelper.getStringSync(null, url);
		Log.i("interface", "result" + result);
		
		ModelBean d = gson.fromJson(result, ModelBean.class);
		if (d != null && !d.getCode().equals(-1)) {
			WebInterfaceApp wa = (WebInterfaceApp) d.getData(WebInterfaceApp.class);
			if (wa != null && d.getData() != null) {
				return wa.getName();
			}
		}
		return null;
	}

	// 请求一个“呼叫”
	public static String getCalling(String mac, int status) {
		Log.i("call", "呼叫.................");
		if(MyApplication.getDeviceInfo() == null){
			Log.e("call", "MyApplication.getDeviceInfo() == null");
			return "无法判断呼叫的异常";
		}
		
		String url = MyApplication.getHost() + PROJECT + "/api/call.json?mac=" + mac + "&content=呼叫:"
				+ MyApplication.getDeviceInfo().getCategoryName() + "-" + MyApplication.getDeviceInfo().getName() + ","
				+ "呼叫" + "&status=" + status;
		Log.i("call", url);
		Looper.prepare();
		try {
			String result = HttpHelper.getStringSync(null, url);
			Log.i("call", result);
			return result;
		} catch (Throwable e) {
			Log.e("call", e.getMessage());
			e.printStackTrace();
		}
		Looper.loop();
		return "无法判断呼叫的异常";
	}

	public static void reportMyIpAddr(String mac, String ip) {
		Log.i("IP", "上报IP.................");
		String url = MyApplication.getHost() + PROJECT + "/api/update-ip.json?mac=" + mac + "&ip=" + ip;
		try {
			HttpHelper.getStringSync(null, url);
		} catch (Throwable e) {
			Log.e("IP", "上报IP出错." + e.getMessage());
		}
	}
 
	public static void getExpSetting(String mac) throws HttpRequestFailException {
		String url = MyApplication.getHost() + PROJECT + "/api/expand.json?mac=" + mac;
		String result = HttpHelper.getStringSync(null, url);
		Log.i("expsetting", "result" + result);

		ModelBean d = gson.fromJson(result, ModelBean.class);
		if (d != null && !d.getCode().equals(-1) && d.getData() != null) {
			ExpConfInfo ei = (ExpConfInfo) d.getData(ExpConfInfo.class);
			try {
				SysConf.expParse(ei.getExtendconf());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private static List<NameValuePair> paramMac(String mac) {
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("mac", mac));
		return params;
	}

}
